// pages/user/login/login.js
const md5 = require('../../../utils/md5.js')
const common = require('../../../utils/util.js')
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        unionID: 1,
        nowDate: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        this.setData({
            nowDate: new Date().getTime()
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        wx.hideLoading()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    formGo: function(e) {
        wx.setStorageSync('loginFormid', e.detail.formId)
    },

    getPhoneNumber: function(e) {
        const that = this
        if (e.detail.errMsg == 'getPhoneNumber:ok') {
            wx.showLoading({
                title: '登录中...',
            })
            let loginData
            if (wx.getStorageSync('userShare')) {
                loginData = {
                    login_type: 2,
                    encryptedData: e.detail.encryptedData,
                    iv: e.detail.iv,
                    code: wx.getStorageSync('code'),
                    belong_refer: wx.getStorageSync('userShare')
                }
            } else {
                loginData = {
                    login_type: 2,
                    encryptedData: e.detail.encryptedData,
                    iv: e.detail.iv,
                    code: wx.getStorageSync('code')
                }
            }
            wx.request({
                url: 'https://www.meiboshi.vip/api/Login/phone_bing',
                header: {
                    'content-type': 'application/x-www-form-urlencoded'
                },
                method: 'POST',
                data: loginData,
                success: function(res) {
                    wx.login({
                        success(loginRes) {
                            wx.setStorageSync('code', loginRes.code)
                        }
                    })
                    console.log(res)
                    const data = res.data.datas
                    if (res.data.code == 204) {
                        wx.hideLoading()
                        wx.showModal({
                            title: '提示',
                            content: '网络繁忙，请重新登录',
                            showCancel: false,
                            success(res) {}
                        })
                    } else {
                        wx.hideLoading()
                        wx.setStorageSync('loginStatus', false)
                        wx.setStorageSync('token', data.token)
                        wx.setStorageSync("roleType", data.role_type)
                        wx.setStorageSync("storeType", data.store_type)
                        wx.setStorageSync("storeId", data.store_id)
                        wx.setStorageSync("userId", data.user_id)
                        wx.setStorageSync("userPhone", data.phone)
                        wx.setStorageSync("userInformation", data.information)
                        //注册formId
                        common.post('User/up_form_id', {
                            form_id: wx.getStorageSync('loginFormid')
                        }).then(function(res) {}).catch(function(e) {})
                        //浏览记录
                        common.post('Userbrowse/add_user_browse', {
                            type: 1,
                            client: 1
                        }).then(function(res) {}).catch(function(e) {})
                        if (data.is_unoid == 0) {
                            that.setData({
                                unionID: 0
                            })
                            wx.setStorageSync('unionID', 0)
                        } else {
                            wx.setStorageSync('unionID', 1)
                            // let pages = getCurrentPages(); //获取当前页面实例
                            // let prePage = pages[pages.length - 2]
                            // prePage.data.isLoading = false
                            // prePage.onLoad(prePage.options); //调用实例的onLoad方法重新加载数据;
                            // prePage.onShow();
                            // wx.navigateBack({
                            //     delta: 1
                            // })
                            if (wx.getStorageSync('prePageUrl') == '/pages/index/index' || wx.getStorageSync('prePageUrl') == '/pages/cart/cart' || wx.getStorageSync('prePageUrl') == '/pages/user/userCenterNew/userCenterNew') {
                                wx.switchTab({
                                    url: wx.getStorageSync('prePageUrl')
                                })
                            } else {
                                wx.redirectTo({
                                    url: wx.getStorageSync('prePageUrl')
                                })
                            }
                        }
                    }
                }
            })
        }
    },

    getUserInfo: function(e) {
        const that = this
        if (e.detail.errMsg == 'getUserInfo:ok') {
            wx.showLoading({
                title: '加载中',
            })
            let data = {}
            let key = wx.getStorageSync('token')
            let sign = 'cds'
            let timestamp = Date.parse(new Date())
            data.code = wx.getStorageSync('code')
            data.phone = wx.getStorageSync('userPhone')
            data.wx_sm = 1
            data.encryptedData = e.detail.encryptedData
            data.iv = e.detail.iv
            data.login_type = 2
            data.key = key
            data.timestamp = timestamp
            data = that.objKeySort(data)
            for (let i in data) {
                sign += (i + data[i])
            }
            sign += 'cds'
            sign = md5(sign)
            data.sign = sign
            wx.request({
                url: 'https://www.meiboshi.vip/api/Login/phone_unionid',
                header: {
                    'content-type': 'application/x-www-form-urlencoded'
                },
                method: 'POST',
                data: data,
                success: function(res) {
                    wx.login({
                        success(loginRes) {
                            wx.setStorageSync('code', loginRes.code)
                        }
                    })
                    const data = res.data.datas
                    if (res.data.code == 204) {
                        wx.hideLoading()
                        wx.setStorageSync('unionID', 0)
                        wx.showModal({
                            title: '提示',
                            content: '网络繁忙，请重新授权',
                            showCancel: false,
                            success(res) {}
                        })
                    } else {
                        wx.hideLoading()
                        wx.setStorageSync('unionID', 1)
                        // let pages = getCurrentPages(); //获取当前页面实例
                        // let prePage = pages[pages.length - 2]
                        // prePage.data.isLoading = false
                        // prePage.onLoad(prePage.options); //调用实例的onLoad方法重新加载数据;
                        // prePage.onShow();
                        // wx.navigateBack({
                        //     delta: 1
                        // })
                        if (wx.getStorageSync('prePageUrl') == '/pages/index/index' || wx.getStorageSync('prePageUrl') == '/pages/cart/cart' || wx.getStorageSync('prePageUrl') == '/pages/user/userCenterNew/userCenterNew') {
                            wx.switchTab({
                                url: wx.getStorageSync('prePageUrl')
                            })
                        } else {
                            wx.redirectTo({
                                url: wx.getStorageSync('prePageUrl')
                            })
                        }
                    }
                }
            })
        }
        // else {
        //     wx.setStorageSync('unionID', 0)
        //     // let pages = getCurrentPages(); //获取当前页面实例
        //     // let prePage = pages[pages.length - 2]
        //     // prePage.data.isLoading = false
        //     // prePage.onLoad(prePage.options); //调用实例的onLoad方法重新加载数据;
        //     // prePage.onShow();
        //     // wx.navigateBack({
        //     //     delta: 1
        //     // })
        //     wx.redirectTo({
        //         url: wx.getStorageSync('prePageUrl')
        //     })
        // }
    },

    objKeySort: function(obj) {
        let newkey = Object.keys(obj).sort()
        let newObj = {}
        for (let i = 0; i < newkey.length; i++) {
            newObj[newkey[i]] = obj[newkey[i]]
        }
        return newObj
    },

    phoneLogin: function(e) {
        wx.setStorageSync('loginFormid', e.detail.formId)
        wx.navigateTo({
            url: '/pages/user/bindPhone/bindPhone',
        })
    },

    goHome: function() {
        wx.setStorageSync('loginStatus', false)
        wx.switchTab({
            url: '/pages/index/index'
        })
    }
})